#include "doctor_chatlistwidget.h"
#include "ui_doctor_chatlistwidget.h"
#include "../../network/networkclient.h"
#include "../common/chatwindow.h"
#include <QJsonObject>
#include <QJsonArray>
#include <QPushButton>
#include <QLabel>
#include <QHBoxLayout>

DoctorChatListWidget::DoctorChatListWidget(int doctorId, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DoctorChatListWidget),
    m_doctorId(doctorId)
{
    ui->setupUi(this);
    
    // 设置表格
    ui->patientTable->setColumnCount(5);
    ui->patientTable->setHorizontalHeaderLabels({"患者ID", "姓名", "性别", "未读消息", "操作"});
    ui->patientTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->patientTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->patientTable->horizontalHeader()->setStretchLastSection(false);
    ui->patientTable->setColumnWidth(0, 80);
    ui->patientTable->verticalHeader()->setDefaultSectionSize(40);
    ui->patientTable->setColumnWidth(1, 150);
    ui->patientTable->setColumnWidth(2, 80);
    ui->patientTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
    ui->patientTable->setColumnWidth(4, 120);
    
    // 隐藏行号列避免乱码
    ui->patientTable->verticalHeader()->setVisible(false);
    
    // 连接网络消息
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &DoctorChatListWidget::onMessageReceived);
    
    // 创建刷新定时器（每5秒刷新一次）
    m_refreshTimer = new QTimer(this);
    connect(m_refreshTimer, &QTimer::timeout, this, &DoctorChatListWidget::refreshPatientList);
    m_refreshTimer->start(5000);
    
    // 加载患者列表
    loadPatients();
}

DoctorChatListWidget::~DoctorChatListWidget()
{
    delete ui;
}

void DoctorChatListWidget::loadPatients() {
    QJsonObject request;
    request["doctor_id"] = m_doctorId;
    NetworkClient::instance().sendRequest(MSG_GET_CHAT_PATIENTS, request);
}

void DoctorChatListWidget::refreshPatientList() {
    loadPatients();
}

void DoctorChatListWidget::updatePatientTable(const QJsonArray& patientsArray) {
    ui->patientTable->setRowCount(patientsArray.size());
    
    for (int i = 0; i < patientsArray.size(); ++i) {
        QJsonObject patientObj = patientsArray[i].toObject();
        
        int patientId = patientObj["id"].toInt();
        QString realName = patientObj["real_name"].toString();
        QString gender = patientObj["gender"].toString();
        int unreadCount = patientObj["unread_count"].toInt();
        
        ui->patientTable->setItem(i, 0, new QTableWidgetItem(QString::number(patientId)));
        ui->patientTable->setItem(i, 1, new QTableWidgetItem(realName));
        ui->patientTable->setItem(i, 2, new QTableWidgetItem(gender));
        
        // 未读消息显示
        QString unreadText = unreadCount > 0 ? 
            QString("🔴 %1 条未读").arg(unreadCount) : "无新消息";
        QTableWidgetItem* unreadItem = new QTableWidgetItem(unreadText);
        if (unreadCount > 0) {
            unreadItem->setForeground(QBrush(QColor("#F56C6C")));
            QFont font = unreadItem->font();
            font.setBold(true);
            unreadItem->setFont(font);
        }
        ui->patientTable->setItem(i, 3, unreadItem);
        
        // 添加"沟通"按钮
        // 创建按钮容器实现居中
        QPushButton* chatBtn = new QPushButton("沟通");
        chatBtn->setMinimumHeight(30);
        chatBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        chatBtn->setProperty("patientId", patientId);
        chatBtn->setProperty("patientName", realName);
        connect(chatBtn, &QPushButton::clicked, this, &DoctorChatListWidget::onChatButtonClicked);
        
        ui->patientTable->setCellWidget(i, 4, chatBtn);
    }
    
    // 更新患者总数
    ui->totalLabel->setText(QString("共 %1 位患者").arg(patientsArray.size()));
}

void DoctorChatListWidget::openChatWindow(int patientId, const QString& patientName) {
    // 从表格中获取患者性别信息
    QString patientInfo = "";
    for (int i = 0; i < ui->patientTable->rowCount(); ++i) {
        if (ui->patientTable->item(i, 0)->text().toInt() == patientId) {
            QString gender = ui->patientTable->item(i, 2)->text();
            patientInfo = "患者 | " + gender;
            break;
        }
    }
    
    ChatWindow* chatWindow = new ChatWindow(m_doctorId, patientId, patientName, patientInfo, this);
    chatWindow->setWindowModality(Qt::ApplicationModal);
    chatWindow->show();
    
    // 打开聊天窗口后，刷新列表以更新未读消息数
    QTimer::singleShot(500, this, &DoctorChatListWidget::loadPatients);
}

void DoctorChatListWidget::onChatButtonClicked() {
    QPushButton* btn = qobject_cast<QPushButton*>(sender());
    if (btn) {
        int patientId = btn->property("patientId").toInt();
        QString patientName = btn->property("patientName").toString();
        openChatWindow(patientId, patientName);
    }
}

void DoctorChatListWidget::onMessageReceived(MessageType type, const QJsonObject& data) {
    if (type == MSG_GET_CHAT_PATIENTS_RESPONSE) {
        if (data["success"].toBool()) {
            QJsonArray patientsArray = data["patients"].toArray();
            updatePatientTable(patientsArray);
        } else {
            // 如果没有患者，显示空表格
            ui->patientTable->setRowCount(0);
            ui->totalLabel->setText("共 0 位患者");
        }
    }
}

